<template>
  <div class="login-account">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      status-icon
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="account">
        <el-input
          v-model="ruleForm.account"
          type="text"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <div>
        <el-checkbox
          v-model="isKeepPassword"
          label="记住我"
          @change="changeKeep"
        ></el-checkbox>
      </div>

      <el-form-item>
        <el-button type="primary" @click="submitForm"> 登陆 </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { rules } from '../config/account-config'
import { ElForm } from 'element-plus'
import ls from '@/utils/cache'
export default defineComponent({
  name: 'LoginAccount',
  setup () {
    const store = useStore()
    const ruleForm = reactive({
      account: ls.getCache('account') ?? '',
      password: ls.getCache('password') ?? ''
    })
    const isKeepPassword = ref(true)
    // 定义实体类型
    // InstanceType<typeof ElForm> 可以由 InstanceType 构造一个 ElForm 类型
    const ruleFormRef = ref<InstanceType<typeof ElForm>>()
    const changeKeep = (value: boolean) => {
      isKeepPassword.value = value
    }
    const submitForm = async () => {
      // await 确保拿到 validate 函数中参数的回调函数的值之后调用
      await ruleFormRef.value?.validate((valid) => {
        if (valid) {
          // 1.登陆，成功后才选择是否保存
          store
            .dispatch('login/accountLoginAction', {
              name: ruleForm.account,
              password: ruleForm.password
            })
            .then((res) => {
              // 2.判断是否需要记录密码
              if (res && isKeepPassword.value) {
                ls.setCache('account', ruleForm.account)
                ls.setCache('password', ruleForm.password)
              } else {
                ls.deleteCache('account')
                ls.deleteCache('password')
              }
            })
        }
      })
    }
    return {
      ruleForm,
      ruleFormRef,
      rules,
      isKeepPassword,
      changeKeep,
      submitForm
    }
  }
})
</script>

<style scoped lang="less">
:deep(.el-button--primary) {
  width: 100%;
}
:deep(.el-checkbox:last-of-type) {
  margin-left: 205px;
}
</style>
